package com.markerhub.Shiro;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.markerhub.Util.JwtUtils;
import com.markerhub.common.lang.Result;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取来自前端头部JWT的token
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String jwt=request.getHeader("Authorization");


        if (StringUtils.isEmpty(jwt)){
            return null; //头部为空，无法生成token
        }
        //jwt不是空的。接收token
        return new JwtToken(jwt);
    }

    //token生成后进行拦截处理
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String jwt=request.getHeader("Authorization");
        if (StringUtils.isEmpty(jwt)){
            return true; //无jwt。不拦截
        }else{
            //校验jwt
           Claims claim = jwtUtils.getClaimByToken(jwt);

           //jwt为空或过期
           if(claim == null || jwtUtils.isTokenExpired(claim.getExpiration())){
               throw new ExpiredCredentialsException("Token已失效，请重新登录!");
           }

           //校验成功。执行登录
            return executeLogin(servletRequest, servletResponse); //拿到token。去realm登录
        }
    }

//  出现异常，将异常返回给前端
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        HttpServletResponse httpServletResponse=(HttpServletResponse) response;

        Throwable throwable=e.getCause()==null ? e: e.getCause(); //返回异常

        Result result=Result.fail(throwable.getMessage()); //输出具体异常

        String json=JSONUtil.toJsonStr(result); //转成json格式

        try {
            httpServletResponse.getWriter().print(json);
        } catch (IOException ex) {

        }

        return false;
    }


    //解决跨域
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
